package com.itheima.controller;

import cn.hutool.core.lang.UUID;

import com.aliyun.oss.*;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * @author CSY
 * 2022/5/10    13:36
 */
@RestController
@Slf4j
@RequestMapping("/common")
@PropertySource(value = {"classpath:aliyun.properties"})
public class CommonController {

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.bucketName}")
    private String bucketName;
    @Value("${aliyun.urlPrefix}")
    private String urlPrefix;

//
//    @GetMapping("/download")
//    public void download(HttpServletResponse response,@RequestParam String name) {
//
//       // name = name.substring();
//        String pathName = "D:\\img";
//        String objectName = name;
//        InputStream in = null;
//        try {
//            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
//            ObjectMetadata object = ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
//            log.info(String.valueOf(object));
//            OutputStream outputStream = response.getOutputStream();
//
//            byte buf[] = new byte[2048];
//            int length = 0;
//            // 输出文件
//            while ((length = in.read(buf)) > 0) {
//                outputStream.write(buf, 0, length);
//            }
//            // 关闭输出流
//            outputStream.close();
//        } catch (Exception e) {
//            log.error("获取文件错误:", e);
//        }
//
//    }
//
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {

        //获取到上传文件的文件名（也可以自己定义）
        String originalFilename = file.getOriginalFilename();


        //动态获取文件后缀名
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID生成文件名,拼接字符串
        String objectName = bucketName + UUID.randomUUID().toString() + suffix;

        String fileUrl = "https://" + bucketName + "." + endpoint +"/"+ objectName;

        OSS ossClient = null;


        try {
            InputStream inputStream = file.getInputStream();
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


            ossClient.putObject(bucketName, objectName,inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileUrl);
    }

}